package cn.exrick.xboot.modules.ReportExcel;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xddf.usermodel.BlackWhiteMode;
import org.apache.poi.xssf.usermodel.*;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class ExportExcelUtile {
    /**
     * @Title: exportExcel
     * @Description: 导出Excel的方法
     * @param workbook
     * @param sheetNum (sheet的位置，0表示第一个表格中的第一个sheet)
     * @param sheetTitle  （sheet的名称）
     * @param headers    （表格的标题）
     * @param result   （表格的数据）
     * @throws Exception
     */
    public Boolean exportExcel(XSSFWorkbook workbook, int sheetNum,
                               String sheetTitle, String[] headers, List<Map<String,String>> result) {
        Boolean res = false ;
        try{
            // 生成一个表格
            XSSFSheet sheet = workbook.createSheet();
            workbook.setSheetName(sheetNum, sheetTitle);
            // 设置表格默认列宽度为20个字节
            sheet.setDefaultColumnWidth((short) 20);
            // 生成一个样式
            XSSFCellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setWrapText(true);

            // 生成一个字体
            Font headerFont = workbook.createFont();
            headerFont.setFontName("Arial");
            headerFont.setFontHeightInPoints((short) 10);
            headerFont.setBold(true);
            headerFont.setColor(IndexedColors.WHITE.getIndex());

            // 把字体应用到当前的样式
            /*style.setFont(headerFont);

            // 指定当单元格内容显示不下时自动换行
            style.setWrapText(true);*/

            // 产生表格标题行
            XSSFRow row = sheet.createRow(0);
            for (int i = 0; i < headers.length; i++) {
                XSSFCell cell = row.createCell((short) i);

                /*cell.setCellStyle(style);*/
                XSSFRichTextString xssfRichTextString = new XSSFRichTextString(headers[i]);
                cell.setCellValue(xssfRichTextString.toString());
            }
            String i = "";
            // 遍历集合数据，产生数据行
            if (result != null) {
                int index = 1;
                for (Map<String, String> m : result) {
                    List<String> stringList = new ArrayList<>();
                    if(index==1){
                        i=m.get("id");
                    }
                    if(!m.get("id").startsWith(i)){
                        index=index+1;
                        row = sheet.createRow(index);
                        i=m.get("id");
                    }else {
                        row = sheet.createRow(index);
                    }

                    int cellIndex = 0;
                        for (String str : m.keySet()) {
                        XSSFCell cell = row.createCell((short) cellIndex);
                        cell.setCellValue(m.get(str));
                        cell.setCellStyle(cellStyle);
                        cellIndex++;
                    }
                    index++;
                }
            }
            res = true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return res;
    }
    public void getExportedFile(XSSFWorkbook workbook, String name, HttpServletResponse response) throws Exception {
        BufferedOutputStream fos = null;
        try {
            String fileName = name + ".xlsx";
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
            fos = new BufferedOutputStream(response.getOutputStream());
            workbook.write(fos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                fos.close();
            }
        }
    }
}
